using System.IO;
using System.Web;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
using System.ComponentModel.DataAnnotations;

namespace DreamHome.Pages;
public class ResourceModel : PageModel
{
    [BindProperty]
    public List<IFormFile> UploadFiles { get; set; }
    public bool UploadToDownload { get; set; } = true;
    public IDirectoryContents DownloadFiles { get; private set;}
    public string? Msg { get; set; }
    private IFileProvider provider { init; get;}
    private readonly ILogger<ResourceModel> _logger;
    public readonly long _fileSizeLimit;
    public readonly string _targetFilePath;
    public readonly string _downloadFilesPath;
    public ResourceModel(ILogger<ResourceModel> logger, IConfiguration config)
    {
        _logger = logger;
        _fileSizeLimit = config.GetValue<long>("FileSizeLimit");
        _targetFilePath = config.GetValue<string>("StoredFilesPath");
        _downloadFilesPath = config.GetValue<string>("StoredTempFilesPath");
        provider = new PhysicalFileProvider(_downloadFilesPath);
        DownloadFiles = provider.GetDirectoryContents(string.Empty);
        UploadFiles = new List<IFormFile>();
    }

    public void OnPostHandler(List<IFormFile> files, bool UploadToDownload)
    {
        try
        {
            long size = files.Sum(f => f.Length);
            if(size >= _fileSizeLimit)
            {
                UploadFiles.Clear();
                throw new IOException("文件过大！");
            }

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    if(UploadToDownload)
                    {
                        var filePath = Path.Combine(_downloadFilesPath, formFile.FileName);
                        using (var stream = System.IO.File.Create(filePath))
                        {
                            formFile.CopyTo(stream);
                        }
                    }
                    else
                    {
                        var trustedFileNameForFileStorage = Path.GetRandomFileName().Replace('.', ' ') + Path.GetExtension(formFile.FileName);
                        var filePath = Path.Combine(
                            _targetFilePath, trustedFileNameForFileStorage);

                        using (var stream = System.IO.File.Create(filePath))
                        {
                            formFile.CopyTo(stream);
                        }
                    }
                }
            }            
        }
        catch (System.Exception e)
        {
            Msg = e.Message;
        }
    }

    public IActionResult OnPostDownload(string? filename)
    {
        if(filename != null)
        {
            var addrUrl = _downloadFilesPath + '\\' + filename;
            var stream = System.IO.File.OpenRead(addrUrl);
            
            return File(stream, "application/octet-stream", Path.GetFileName(addrUrl));
        }
        return BadRequest();
    }
    public IActionResult OnPostDelete(string? filename)
    {
        if(filename != null)
        {
            var addrUrl = _downloadFilesPath + '\\' + filename;
            System.IO.File.Delete(addrUrl);
        }
        return RedirectToPage("./Resource", "Handler");
    }

    public void OnGet(string? msg)
    {
        Msg = msg;
    }

}
